package com.supor.aiot.mine.ui.mine;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.google.gson.reflect.TypeToken;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.app.api.FileUploadImpl;
import com.supor.aiot.common.app.api.UserImpl;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UploadResultBean;
import com.supor.aiot.common.entity.UserInfo;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

public class MineAccountViewModel extends BaseViewModel {

    private MutableLiveData<Result> ageData = new MutableLiveData<>();
    private MutableLiveData<Result> uploadResult = new MutableLiveData<>();
    private MutableLiveData<Result> updateResult = new MutableLiveData<>();
    private MutableLiveData<Result> logoutResult = new MutableLiveData<>();

    public MineAccountViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Result> getAgeData() {
        return ageData;
    }

    public MutableLiveData<Result> getUploadResult() {
        return uploadResult;
    }

    public MutableLiveData<Result> getUpdateResult() {
        return updateResult;
    }

    public MutableLiveData<Result> getLogoutResult() {
        return logoutResult;
    }

    /**
     * 获取年代字典
     */
    @SuppressLint("CheckResult")
    public void getAgeList() {
        UserImpl.getInstance().getDictionary("CHRONOLOGY", 1, 100).subscribe(result -> {
            if (result.isSuccess()) {
                ageData.setValue(new Result.Success<>(result.data.rows));
            } else {
                ageData.setValue(new Result.Error("getAgeList failed"));
                Logc.e("accept: failed");
            }
        }, throwable -> {
            ageData.setValue(new Result.Error(new Exception(throwable)));
            Logc.e("getAgeList: " + throwable);
        });
    }

    /**
     * 上传图片
     *
     * @param userInfo
     */
    @SuppressLint("CheckResult")
    public void uploadPhoto(UserInfo userInfo) {
        List<File> files = new ArrayList<>();
        File file = new File(userInfo.getFaceImage());
        files.add(file);
        
        FileUploadImpl.getInstance().uploadFiles("photo", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                userInfo.setFaceImage(uploadResultBeans.get(0).getFileUrl());
                updateUser(userInfo);
            } else {
                uploadResult.setValue(new Result.Error("upload photo failed"));
            }
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            uploadResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    @SuppressLint("CheckResult")
    public void updateUser(UserInfo userInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("providerId", "0");
        map.put("bossUserId", userInfo.getBossUserId());
        map.put("faceImage", userInfo.getFaceImage());
        map.put("nickName", userInfo.getNickName());
        if (!TextUtils.isEmpty(userInfo.getChronology())) {
            map.put("chronology", userInfo.getChronology());
        }
        if (!TextUtils.isEmpty(userInfo.getSex())) {
            map.put("sex", userInfo.getSex());
        }
        UserImpl.getInstance().updateUser(userInfo.getBossUserId(), map).subscribe(apiResult -> {
            if (apiResult.isSuccess()) {
                // 更新用户成功后重新获取下用户信息
                getUser(userInfo.getBossUserId());
            } else {
                updateResult.setValue(new Result.Error("updateUser failed"));
            }
        }, throwable -> {
            Logc.e("updateUser: " + throwable);
            updateResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    /**
     * 获取用户信息
     *
     * @param id 用户ID
     */
    @SuppressLint("CheckResult")
    public void getUser(String id) {
        UserImpl.getInstance().getUser(id).subscribe(apiResult -> {
            if (apiResult.isSuccess()) {
                SuporPresenter.getInstance().saveInfo(apiResult.data, false);
                RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.SUCCESS);
                updateResult.setValue(new Result.Success(apiResult.data));
            } else {
                updateResult.setValue(new Result.Error("getUser failed"));
            }
        }, throwable -> {
            Logc.e("getUser: " + throwable);
            updateResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    @SuppressLint("CheckResult")
    public void logout() {
        UserImpl.getInstance().logout().subscribe(apiResult -> {
            if (apiResult.isSuccess()) {
                logoutResult.setValue(new Result.Success(Constants.Value.SUCCESS));
            } else {
                logoutResult.setValue(new Result.Error("logout failed"));
            }
        }, throwable -> {
            Logc.e("logout: " + throwable);
            logoutResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }
}
